let uploadedFile = null;

function previewImage() {
    const input = document.getElementById('fileInput');
    const preview = document.getElementById('preview');
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function (e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
            uploadedFile = input.files[0];
        };
        reader.readAsDataURL(input.files[0]);
    }
}

function submitImage() {
    if (!uploadedFile) {
        alert("请上传图片！");
        return;
    }

    const formData = new FormData();
    formData.append("image", uploadedFile);

    fetch("/predict", {
        method: "POST",
        body: formData,
    })
        .then(res => res.json())
        .then(data => {
            if (data.error) {
                alert(data.error);
            } else {
                document.getElementById("result").innerHTML = `
                    <strong>预测类别：</strong> ${data.prediction} <br/>
                    <strong>概率详情：</strong><br/>
                    ${Object.entries(data.probs).map(([cls, prob]) => `${cls}：${prob}%`).join("<br>")}
                `;
            }
        });
}
